package com.example.block_chain.utils;

import com.example.block_chain.domain.pojo.School;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
 *@description: 按学校多级组织多分支区块链接口
 *@author: hisen
 *@Time: 2024/2/15  23:30
 */

public class KeyValueReaderUtil {
    public static String getDigestByCode(String code, String filePath) {
        Map<String, String> keyValueMap = new HashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] keyValue = line.split("="); // 假设键值对之间使用等号分隔
                if (keyValue.length == 2) { // 确保分割后有两个元素，否则跳过当前行
                    String key = keyValue[0].trim();
                    String value = keyValue[1].trim();
                    keyValueMap.put(key, value);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return keyValueMap.get(code);
    }

    public static List<School> getSchool(String filePath) {
        List<School> list = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] keyValue = line.split("="); // 假设键值对之间使用等号分隔
                if (keyValue.length == 2) { // 确保分割后有两个元素，否则跳过当前行
                    String key = keyValue[0].trim();
                    String value = keyValue[1].trim();
                    list.add(new School(key, value));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void addStringIntoFile(String filePath, String value) {
        String newContent = "\n" + value;
        try {
            Path path = Paths.get(filePath);
            Files.write(path, newContent.getBytes(), StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
